package com.project.nimsen.web.pub.tag;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.project.nimsen.constant.NimsenConstant;
import com.project.nimsen.dto.UrlinfoDto;
import com.project.nimsen.service.IUrlinfoService;
import com.project.nimsen.util.NimsenUtil;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
/**
 * 用于得url信息
 * */
@Component("nimsen_url")
public class UrlTag extends BaseTag {
	@Resource
	IUrlinfoService urlinfoService;
	/**
	 * @param id 得到URL对应的主体编号，默认为当前编号
	 * @param urltype URL类型,archivesurl为文章URL类型,默认为archivesurl
	 * @param file 必填,要输出的字段url返回附件的url,urlname URL的名称,
	 * 		  urldesc URL的描述
	 * @param order ASC为升序，DESC为降序，默认为ASC
	 * @param num 得到的第个URL信息
	 * */
	protected void exec(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		String file = getParam("file");
		//必填项验证
		if(StringUtils.isBlank(file))
			return;
		//URL类型
		String urltype = getParam("urltype");
		if(StringUtils.isBlank(urltype))
			urltype = NimsenConstant.ARCHIVES_URL_LIST;
		//编号
		String id = getParam("id");
		if(StringUtils.isBlank(id)){
			String curid = null;
			if(NimsenConstant.ARCHIVES_URL_LIST.equals(urltype)){
				
			}else{
				curid = getAttr("archid");
			}
			//如果当前文章编号也为空则返回
			if(StringUtils.isBlank(curid))
				return;
			id = curid;
		}
		UrlinfoDto dto = new UrlinfoDto();
		dto.setUrloutable(urltype);
		dto.setUrloutid(id);
		String order = getParam("order");
		if("DESC".equals(order))
			dto.setOrderType("DESC");
		else
			dto.setOrderType("ASC");
		try {
			//得到要查询的url集合
			List<Map<String, Object>> list = urlinfoService.findTagUrlByDto(dto);
			if(CollectionUtils.isEmpty(list))
				return;
			//得到的第个URL信息
			Integer num = getIntegerParam("num");
			if(num==null||num<1)
				num = 1;
			//如果用户要显示的大于总附件则返回最后一个
			if(num>list.size())
				num = list.size();
			num = num-1;
			//得到要返回的附件信息
			Map<String, Object> map = list.get(num);
			//输出相应的信息
			if("url".equals(file)){
				outWrite(NimsenUtil.obj2String(map.get("url")));
			}else if("urlname".equals(file)){
				outWrite(NimsenUtil.obj2String(map.get("urlname")));
			}else if("urldesc".equals(file)){
				outWrite(NimsenUtil.obj2String(map.get("urldesc")));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
